<template>
  <el-carousel :interval="3000" arrow="hover" class="banner">
    <el-carousel-item v-for="(item, index) in bannerList" :key="index">
      <el-image
        :src="item.imageSrc"
        class="banner_src"
        fit="contain"
      >
        <div slot="error" class="image-slot">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
    </el-carousel-item>
  </el-carousel>
</template>

<script setup>
import { onMounted, ref } from "vue";
import BannerApi from "@/api/product/banner";
import { useBanner } from "@/pinia/modules/banner";

const bannerStore = useBanner();

const bannerList = ref([]);

onMounted(() => {
  // 从本地缓存拿
  const bannerCache = bannerStore.getBanner();
  if (bannerCache != null && bannerCache.length !== 0) {
    bannerList.value = bannerCache;
  }
  // 本地缓存没有，请求后端
  else {
    fetchData();
  }
});

// 请求数据获取Banner
const fetchData = async () => {
  const { data } = await BannerApi.showBanner();
  bannerStore.saveBanner(data);
  bannerList.value = bannerStore.getBanner();
};

</script>

<style scoped lang="scss">
.banner {
  margin: 0 auto;
  width: 1000px;
  height: 580px;

  :deep(.el-carousel__container) {
    height: 100%;
  }

  .banner_src {
    width: 100%;
    height: 100%;
  }
}
</style>
